package com.youlai.netty.service.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zc
 * @date 2023-02-04 22:25
 */
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
        private SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            //1.获取Channel通道
            final Channel channel=ctx.channel();

            //2.创建一个定时线程池
            ScheduledExecutorService ses= Executors.newScheduledThreadPool(1);
            //3.一秒钟之后只需，并且每隔5秒往浏览器发送数据
            ses.scheduleWithFixedDelay(() -> {
                String sendTime=format.format(new Date());
                channel.writeAndFlush(new TextWebSocketFrame("推送时间=" + sendTime));
            },1,5, TimeUnit.SECONDS);
        }


        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
            log.info("WebSocket收到消息 " + msg.text());
        }
    }


